package org.example.service.v1;

import org.example.exception.DefaultApiException;
import org.example.mapper.UserMapper;
import org.example.pojo.User;
import org.example.service.UserService;
import org.example.util.JsonBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private HttpSession session;

    private void setLogin(User user) {
        session.setAttribute("user", user);
    }

    @Override
    public JsonBody login(User user) throws DefaultApiException {
        User dUser = userMapper.selectByName(user.getName());

        if (dUser == null) {
            throw new DefaultApiException("用户名不存在");
        } else if (!dUser.getPassword().equals(user.getPassword())) {
            throw new DefaultApiException("密码错误");
        } else {
            setLogin(user);
        }

        return JsonBody.ok("登录成功!");
    }

    @Override
    public JsonBody register(User user) throws DefaultApiException {
        if (user.getPassword() == null || user.getPassword().length() < 6){
            throw new DefaultApiException("密码长度不能小于6");
        } else if (user.getName() == null || user.getName().length() < 3) {
            throw new DefaultApiException("用户名长度不能小于3");
        } else {
            User dUser = userMapper.selectByName(user.getName());
            if (dUser != null) {
                throw new DefaultApiException("用户名已存在");
            }
            userMapper.add(user);
            setLogin(user);
        }
        return JsonBody.ok("注册成功!");
    }


}
